package com.xsystem.util;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;

public class GenericDAO {

	private SessionFactory sessionFactory;
	private SessionFactory slaveSessionFactory;

	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	public Session getSlaveSession() {
		return slaveSessionFactory.getCurrentSession();
	}

	@SuppressWarnings("unchecked")
	public <T> T findById(Integer i, Class<T> classType) {
		try {
			return (T) getSessionFactory().getCurrentSession().get(classType, i);
		} catch (HibernateException exception) {
			return null;
		}
	}

	public <T> Integer create(T obj) {
		return (Integer) getSessionFactory().getCurrentSession().save(obj);
	}

	@SuppressWarnings("unchecked")
	public <T> T update(T obj) {
		T object = (T) getSessionFactory().getCurrentSession().merge(obj);
		return object;
	}

	public <T> void delete(T obj) {
		getSessionFactory().getCurrentSession().delete(obj);
	}

	public <T> void deleteById(Integer id, Class<T> classType) {
		Object record = getSessionFactory().getCurrentSession().load(classType, id);
		getSessionFactory().getCurrentSession().delete(record);
	}

	public <T> void refresh(T obj) {
		getSessionFactory().getCurrentSession().refresh(obj);
	}

	public void flush() {
		getSessionFactory().getCurrentSession().flush();
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public SessionFactory getSlaveSessionFactory() {
		return slaveSessionFactory;
	}

	public void setSlaveSessionFactory(SessionFactory slaveSessionFactory) {
		this.slaveSessionFactory = slaveSessionFactory;
	}
	
	@SuppressWarnings("rawtypes")
	public List findByDetachedCriteria(DetachedCriteria detachedCriteria) throws HibernateException {
		return detachedCriteria.getExecutableCriteria(getSession()).list();
	}
	
	public Object findUniqueResultByDetachedCriteria(DetachedCriteria detachedCriteria) throws HibernateException {
		return detachedCriteria.getExecutableCriteria(getSession()).uniqueResult();
	}

}
